// Package database @program: chat
//@author: edte
//@create: 2021-12-28 17:28
package database

import (
	log2 "chat/log"
	"chat/tools"
	"context"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"strconv"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func QuitChatRoom(ctx context.Context, roomId int, userId int) error {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/chats?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})

	//db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/chats?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Error", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("failed to connect database")
	}
	tmpChatRoom := tools.ChatRoomStruct{}
	db.Model(tools.ChatRoomStruct{}).Where("room_id=?", roomId).First(&tmpChatRoom)
	if tmpChatRoom.RoomId == 0 {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", "Chat room does not exist")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("聊天室不存在")
	}
	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       2,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	if tmpChatRoom.RoomId == userId {

		strings, err := rdb.SMembers(ctx, strconv.Itoa(roomId)).Result()
		if err != nil {
			writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
			if writeLog == 200 {
				fmt.Println("成功写入日志")
			}
			if err2 != nil {
				fmt.Println("写入日志失败")
			}
			return err
		}
		for _, s := range strings {
			_, err := rdb.SRem(ctx, strconv.Itoa(roomId), s).Result()
			if err != nil {
				writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
				if writeLog == 200 {
					fmt.Println("成功写入日志")
				}
				if err2 != nil {
					fmt.Println("写入日志失败")
				}
				return err
			}
		}
		return err
	}
	result, err := rdb.SIsMember(ctx, strconv.Itoa(roomId), userId).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	if result == false {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "QuitChatRoom", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", "The account is not in the chat room")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("账号未加入聊天室")
	}
	rdb.SRem(ctx, strconv.Itoa(roomId), userId)
	return err
}
